<template>
  <!-- 营业收入统计-每日消费汇总 -->
  <div class="operating_income_daily_consumption_summary">
    <el-table
      v-loading="loading"
      :data="detailslist"
      ref="table"
      border
      :row-key="getRowKeys"
      highlight-current-row
      :expand-row-keys="expands"
      @expand-change="expandChange"
      :key="Math.random()"
      :header-cell-style="headFirst"
      :cell-style="
        detailsTotal ? (res) => headFirst_col(res, detailslist, 1) : () => {}
      "
    >
      <el-table-column type="expand" width="32px">
        <template slot-scope="scope" v-if="scope.row.pkId != 'end'">
          <el-table
            :data="tableData2"
            v-loading="loading2"
            style="width: 100%"
            row-key="pkId"
            :show-header="status"
            :tree-props="{ children: 'mealList', hasChildren: 'hasChildren' }"
            :cell-style="(res) => headFirst_col(res, [])"
          >
            <el-table-column width="32px"></el-table-column>
            <el-table-column
              prop="consumePlace"
              label="消费场所"
              align="center"
              v-if="formThead2.consumePlace.checked"
              min-width="120px"
            ></el-table-column>
            <el-table-column
              prop="dataMakeTime"
              label="日期"
              align="center"
              v-if="formThead2.dataMakeTime.checked"
              width="90px"
            ></el-table-column>
            <el-table-column
              prop="mealName"
              align="center"
              v-if="formThead2.mealName.checked"
              label="餐别"
              width="60px"
            ></el-table-column>
            <el-table-column
              prop="sumSuccessExpenditure"
              align="center"
              v-if="formThead2.sumSuccessExpenditure.checked"
              label="储值消费"
              width="90px"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.sumSuccessExpenditure | amountyuan }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="consumeReviseCount"
              label="修正次数"
              v-if="formThead2.consumeReviseCount.checked"
              align="center"
              width="60px"
            ></el-table-column>
            <el-table-column
              prop="consumeReviseSum"
              label="修正金额(元)"
              v-if="formThead2.consumeReviseSum.checked"
              align="center"
              width="90px"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.consumeReviseSum | amountyuan }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="sumExpenditure"
              v-if="formThead2.sumExpenditure.checked"
              align="center"
              label="合计"
              min-width="90px"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.sumExpenditure | amountyuan }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="consumeCount"
              align="center"
              v-if="formThead2.consumeCount.checked"
              label="消费人次"
              width="70px"
            ></el-table-column>
            <el-table-column
              prop="userCount"
              align="center"
              v-if="formThead2.userCount.checked"
              label="消费人数"
              width="60px"
            ></el-table-column>
            <el-table-column
              prop="avgExpenditure"
              width="94px"
              align="center"
              v-if="formThead2.avgExpenditure.checked"
              label="平均消费(按次)"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.avgExpenditure | amountyuan }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="avgUserExpenditure"
              width="94px"
              align="center"
              v-if="formThead2.avgUserExpenditure.checked"
              label="平均消费(按人)"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.avgUserExpenditure | amountyuan }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="maxExpenditure"
              width="90px"
              align="center"
              v-if="formThead2.maxExpenditure.checked"
              label="最大消费金额"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.maxExpenditure | amountyuan }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="minExpenditure"
              width="90px"
              align="center"
              v-if="formThead2.minExpenditure.checked"
              label="最小消费金额"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.minExpenditure | amountyuan }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="timesExpenditureCount"
              align="center"
              v-if="formThead2.timesExpenditureCount.checked"
              label="计次消费次数"
              width="85px"
            ></el-table-column>
          </el-table>
          <div class="page1">
            <el-pagination
              @size-change="handleSizeChange2"
              @current-change="handleCurrentChange2"
              :current-page="currentPage2"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize2"
              layout="total, sizes, prev, pager, next, jumper"
              :total="recordCount2"
            ></el-pagination>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="consumePlace"
        label="消费场所"
        v-if="formThead2.consumePlace.checked"
        align="center"
        min-width="120px"
      ></el-table-column>
      <el-table-column
        prop="dataMakeTime"
        label="日期"
        width="90px"
        v-if="formThead2.dataMakeTime.checked"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="mealName"
        label="餐别"
        v-if="formThead2.mealName.checked"
        align="center"
        width="60px"
      ></el-table-column>
      <el-table-column
        prop="sumSuccessExpenditure"
        label="储值消费"
        v-if="formThead2.sumSuccessExpenditure.checked"
        align="center"
        width="90px"
      >
        <template slot-scope="scope">
          <div>{{ scope.row.sumSuccessExpenditure | amountyuan }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="consumeReviseCount"
        label="修正次数"
        v-if="formThead2.consumeReviseCount.checked"
        align="center"
        width="60px"
      ></el-table-column>
      <el-table-column
        prop="consumeReviseSum"
        label="修正金额(元)"
        v-if="formThead2.consumeReviseSum.checked"
        align="center"
        width="90px"
      >
        <template slot-scope="scope">
          <div>{{ scope.row.consumeReviseSum | amountyuan }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="sumExpenditure"
        label="合计"
        v-if="formThead2.sumExpenditure.checked"
        align="center"
        min-width="90px"
      >
        <template slot-scope="scope">
          <div>{{ scope.row.sumExpenditure | amountyuan }}</div>
        </template>
      </el-table-column>

      <el-table-column
        prop="consumeCount"
        label="消费人次"
        v-if="formThead2.consumeCount.checked"
        align="center"
        width="70px"
      ></el-table-column>

      <el-table-column
        prop="userCount"
        label="消费人数"
        v-if="formThead2.userCount.checked"
        align="center"
        width="60px"
      ></el-table-column>

      <el-table-column
        prop="avgExpenditure"
        width="94px"
        label="平均消费(按次)"
        v-if="formThead2.avgExpenditure.checked"
        align="center"
      >
        <template slot-scope="scope">
          <div>{{ scope.row.avgExpenditure | amountyuan }}</div>
        </template>
      </el-table-column>

      <el-table-column
        prop="avgUserExpenditure"
        width="94px"
        label="平均消费(按人)"
        v-if="formThead2.avgUserExpenditure.checked"
        align="center"
      >
        <template slot-scope="scope">
          <div>{{ scope.row.avgUserExpenditure | amountyuan }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="maxExpenditure"
        width="90px"
        label="最大消费金额"
        v-if="formThead2.maxExpenditure.checked"
        align="center"
      >
        <template slot-scope="scope">
          <div>{{ scope.row.maxExpenditure | amountyuan }}</div>
        </template>
      </el-table-column>

      <el-table-column
        prop="minExpenditure"
        label="最小消费金额"
        v-if="formThead2.minExpenditure.checked"
        align="center"
        width="90px"
      >
        <template slot-scope="scope">
          <div>{{ scope.row.minExpenditure | amountyuan }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="timesExpenditureCount"
        align="center"
        v-if="formThead2.timesExpenditureCount.checked"
        label="计次消费次数"
        width="85px"
      ></el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChangepage"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="recordCount"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import bus from '@/bus.js'
export default {
  data() {
    return {
      filename: '每日消费汇总',
      getRowKeys(row) {
        return row.id
      },
      expands: [],
      update: true,

      loading: false,
      // 打印，导出数据
      exportlist: [],
      // 合计数据
      detailsTotal: null,
      detailslist: [],
      pageNum: 1,
      pageSize: 20,
      currentPage: 1,
      recordCount: 0,
      searchInfo: {},
      formThead2: {
        consumePlace: {
          label: '消费场所',
          prop: 'consumePlace',
          checked: true
        },
        dataMakeTime: { label: '日期', prop: 'dataMakeTime', checked: true },
        mealName: { label: '餐别', prop: 'mealName', checked: true },
        sumSuccessExpenditure: {
          label: '储值消费',
          prop: 'sumSuccessExpenditure',
          checked: true
        },
        consumeReviseCount: {
          label: '修正次数',
          prop: 'consumeReviseCount',
          checked: true
        },
        consumeReviseSum: {
          label: '修正金额(元)',
          prop: 'consumeReviseSum',
          checked: true
        },
        sumExpenditure: {
          label: '合计',
          prop: 'sumExpenditure',
          checked: true
        },
        consumeCount: {
          label: '消费人次',
          prop: 'consumeCount',
          checked: true
        },
        userCount: { label: '消费人数', prop: 'userCount', checked: true },
        avgExpenditure: {
          label: '平均消费(按次)',
          prop: 'avgExpenditure',
          checked: true
        },
        avgUserExpenditure: {
          label: '平均消费(按人)',
          prop: 'avgUserExpenditure',
          checked: true
        },
        maxExpenditure: {
          label: '最大消费金额',
          prop: 'maxExpenditure',
          checked: true
        },
        minExpenditure: {
          label: '最小消费金额',
          prop: 'minExpenditure',
          checked: true
        },

        timesExpenditureCount: {
          label: '计次消费次数',
          prop: 'timesExpenditureCount',
          checked: true
        }
      },

      tableData2: [],
      pageNum2: 1,
      pageSize2: 20,
      currentPage2: 1,
      recordCount2: 0,
      loading2: false,
      status: false
    }
  },
  mounted() {
    console.log(1)
    bus.$on('listenToB', this.getHeaderDate)
  },
  props: [
    'datetime',
    'unitGuid',
    'consumptionpoint',
    'radio',
    'consumermachine',
    'mealFlag'
  ],
  methods: {
    // 打印
    async export(type) {
      if (this.recordCount == 0) {
        this.$message({
          message: '请查询数据后,在进行此操作',
          type: 'warning'
        })
        return false
      }
      await this.getEportData()
      if (type == 'print') {
        this.printJS()
      } else {
        this.export2Excel()
      }
    },
    // 打印
    printJS() {
      let someJSONdata = this.exportlist
      const title = '每日消费汇总'
      this.unitName = sessionStorage.getItem('unitName')
      const properties = []
      // 拿到数据,filterValArr为数据值，tHeader为数据标题，一一对应
      const { filterValArr, tHeader } = this.getIsPrint()
      filterValArr.map((item, index) => {
        properties.push({
          displayName: tHeader[index],
          field: filterValArr[index]
        })
      })
      // 打印
      this.$printJS({
        // 眉头
        documentTitle: `${this.unitName}`,
        /**
         * 获取表头的信息
         * @param {*} title 表名
         * @param {*} unitName 单位
         * @param {*} time 时间
         */
        header: this.printHeader(
          title,
          this.unitName,
          `${this.formatDate(
            new Date(this.searchInfo.startTime),
            'yyyy-MM-dd'
          )} 至 ${this.formatDate(
            new Date(this.searchInfo.endTime),
            'yyyy-MM-dd'
          )}`
        ),
        printable: someJSONdata,
        properties: properties,
        type: 'json',
        // 是否每页都显示头部
        // repeatTableHeader:false,
        headerRow: 1,
        /**
         * 获取页脚的信息
         * @param {*} loginName 制表人：
         * @param {*} time 时间
         */
        endPage: this.printFloor(
          sessionStorage.getItem('username'),
          this.getNowTime('yy-mm-dd hh:mm:ss')
        ),
        //  获取页脚的信息样式
        style: this.printFloorStyle()
      })
    },
    // 拿到表头数据
    getIsPrint() {
      const filterValArr = [
        'consumePlace',
        'dataMakeTime',
        'mealName',
        'sumSuccessExpenditure',
        'consumeReviseCount',
        'consumeReviseSum',
        'sumExpenditure',
        'consumeCount',
        'userCount',
        'avgExpenditure',
        'avgUserExpenditure',
        'maxExpenditure',
        'minExpenditure',
        'timesExpenditureCount'
      ]
      let valArr = []
      let tHeader = []
      filterValArr.map(item => {
        if (this.formThead2[item].checked) {
          valArr.push(this.formThead2[item].prop)
          tHeader.push(this.formThead2[item].label)
        }
      })
      return { filterValArr: valArr, tHeader }
    },
    // 获取每日消费汇总的总数据
    getEportData() {
      let _this = this
      return new Promise(function(resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl(
              '/terminal/consume/consume-ever-day-gather-merchant-page'
            ),
            method: 'post',
            data: _this.$http.adornData({
              messageContent: {
                pageNum: 1,
                pageSize: _this.recordCount,
                searchInfo: _this.searchInfo
              },
              messageType: 0
            })
          })
          .then(({ data }) => {
            if (data.messageCode == 200) {
              _this.exportlist = data.messageContent.data
              // 将合计数据添加到最后一行
              if (_this.detailsTotal && _this.exportlist.length) {
                _this.exportlist.push({ ..._this.detailsTotal })
              }
              let fistArr = [
                'sumSuccessExpenditure',
                'consumeReviseSum',
                'sumExpenditure',
                'avgExpenditure',
                'avgUserExpenditure',
                'maxExpenditure',
                'minExpenditure'
              ]
              _this.exportlist.map(item => {
                fistArr.map(fist => {
                  item[fist] = _this.amountyua(item[fist])
                })
              })
              resolve(_this.exportlist)
            } else {
              reject(data.errorMessage)
              _this.$message.error(data.errorMessage)
            }
          })
      })
    },
    // 获取合计数据
    getTotal() {
      let _this = this
      _this.loading = true
      return new Promise(function(resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl(
              '/terminal/consume/consume-ever-day-gather-merchant-total'
            ),
            method: 'post',
            data: _this.$http.adornData({
              messageContent: _this.searchInfo,
              messageType: 0
            })
          })
          .then(({ data }) => {
            _this.loading = false
            if (data.messageCode == 200) {
              resolve(data.messageContent)
            } else {
              reject(data.errorMessage)
              this.$message.error(data.errorMessage)
            }
          })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    // 导出函数
    export2Excel() {
      const nowtime = this.getimeto()
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../excel/Export2Excel')
        const multiHeader = []
        const multiHeader2 = []
        const merges = []
        const { filterValArr, tHeader } = this.getIsPrint()
        const list = this.exportlist
        const data = this.formatJson(filterValArr, list)
        export_json_to_excel({
          multiHeader, //这里是第一行的表头
          multiHeader2, //这里是第二行的表头
          header: tHeader, //这里应该是算第三行的表头
          data,
          merges,
          filename: this.filename + nowtime
        })
      })
    },
    //初始化每日应收费汇总
    async geteverdaygathermerchant() {
      this.pageNum = 1
      this.merchantGuid = ''
      if (this.datetime == null) {
        this.searchInfo.startTime = ''
        this.searchInfo.endTime = ''
      } else {
        this.searchInfo.startTime = this.datetime[0]
        this.searchInfo.endTime = this.datetime[1]
      }
      this.searchInfo.unitGuid = this.unitGuid
      this.searchInfo.merchantGuidList = this.consumptionpoint
      if (this.radio == 0) {
        this.searchInfo.timeType = 0
      } else if (this.radio == 1) {
        this.searchInfo.timeType = 1
      } else {
        this.searchInfo.timeType = 2
      }
      this.searchInfo.mealFlag = this.mealFlag
      this.searchInfo.terminalCodeList = this.consumermachine
      this.detailsTotal = null
      this.detailsTotal = await this.getTotal()
      this.detailsTotal.pkId = 'end'
      this.detailsTotal.merchantGuid = 'end'
      this.geteverdaygathermerchantSeek()
    },
    //获取商户每日应收费汇总
    geteverdaygathermerchantSeek() {
      this.loading = true
      this.$http({
        url: this.$http.adornUrl(
          '/terminal/consume/consume-ever-day-gather-merchant-page'
        ),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            searchInfo: this.searchInfo
          },
          messageType: 0
        })
      }).then(({ data }) => {
        this.loading = false
        if (data.messageCode == 200) {
          if (
            data.messageContent.data.length == 0 ||
            data.messageContent.data == null
          ) {
            this.$message({
              message: '查询成功当前暂无数据',
              type: 'success'
            })
          }
          // this.detailslist=data.messageContent.data
          this.recordCount = data.messageContent.recordCount
          this.currentPage = data.messageContent.pageNum
          this.tableData2 = []
          for (var i = 0; i < data.messageContent.data.length; i++) {
            data.messageContent.data[i].id = i
          }
          this.detailslist = data.messageContent.data
          // 将合计数据添加到最后一行
          if (this.detailsTotal && this.detailslist.length) {
            this.detailslist.push(this.detailsTotal)
          }
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 翻页相关函数
    handleSizeChange(val) {
      this.pageSize = val
      this.geteverdaygathermerchantSeek()
    },
    handleCurrentChangepage(val) {
      this.pageNum = val
      this.geteverdaygathermerchantSeek()
    },
    getHeaderDate(val) {
      this.formThead2 = val
      this.$nextTick(() => {
        this.$refs['table'].doLayout()
      })
      console.log(this.formThead2)
    },
    //
    expandChange(row, expandedRows) {
      console.log(row)
      //   console.log(row)
      var that = this
      if (expandedRows.length) {
        that.expands = []
        if (row) {
          that.expands.push(row.id)
        }
        this.update = false
        this.$nextTick(() => {
          this.update = true
        })
        this.merchantGuid = row.merchantGuid
        this.tableData2 = []
        if (this.datetime == null) {
          this.searchInfo.startTime = ''
          this.searchInfo.endTime = ''
        } else {
          this.searchInfo.startTime = this.datetime[0]
          this.searchInfo.endTime = this.datetime[1]
        }
        this.searchInfo.unitGuid = this.unitGuid
        if (row.merchantGuid == 'end') {
          return
        }
        this.searchInfo.merchantGuid = row.merchantGuid
        if (this.radio == 0) {
          this.searchInfo.timeType = 0
        } else if (this.radio == 1) {
          this.searchInfo.timeType = 1
        } else {
          this.searchInfo.timeType = 2
        }
        this.pageNum2 = 1
        this.geteverdaugatherterminal(row.merchantGuid)
      } else {
        that.expands = []
      }
    },
    //设备每日应收消费
    geteverdaugatherterminal(merchantGuid) {
      console.log(merchantGuid)

      // this.searchInfo.merchantGuid = this.consumptionpoint;
      this.loading2 = true
      this.$http({
        url: this.$http.adornUrl(
          '/terminal/consume/consume-ever-day-gather-terminal-page'
        ),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            pageNum: this.pageNum2,
            pageSize: this.pageSize2,
            searchInfo: this.searchInfo
          },
          messageType: 0
        })
      }).then(({ data }) => {
        this.update = true
        this.loading2 = false
        if (data.messageCode == 200) {
          console.log(data)
          this.tableData2 = data.messageContent.data || []
          this.recordCount2 = data.messageContent.recordCount
          this.currentPage2 = data.messageContent.pageNum
          // this.$nextTick(() => {
          //     this.update = true
          // })
          // for(var i=0;i<this.tableData2.length;i++){
          //  this.tableData2[i].id=[i].toString()
          //  if(this.tableData2[i].mealList!=null&&this.tableData2[i].mealList.length!=0){
          //      for(var j=0;j<this.tableData2[i].mealList.length;j++){
          //         this.tableData2[i].mealList[j].id=i.toString()+j.toString()
          //      }
          //  }
          // }
          console.log(this.tableData2)
          // this.loading2=false
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    handleCurrentChange2(val) {
      this.pageNum2 = val
      this.geteverdaugatherterminal(this.merchantGuid)
    },
    handleSizeChange2(val) {
      this.pageSize2 = val
      this.geteverdaugatherterminal(this.merchantGuid)
    }
  }
}
</script>

<style lang="scss" scoped>
.operating_income_daily_consumption_summary {
  //滚动条的宽度
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #a1a3a9;
    border-radius: 3px;
  }
}
.page,
.page1 {
  display: flex;
  justify-content: center;
  align-items: center;
}
.page {
  // padding-top: 30px;
}
</style>